package com.example.demo;

import com.example.demo.dao.SystemUserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Component
public class GlobalFilter implements Filter {
    String[] whitelist = {
      "/js/","/css/","images/","login.html",
            "/sysuser_login"
    };

    @Autowired
    SystemUserDao systemUserDao;

    @Override
    public void doFilter(ServletRequest req,
         ServletResponse res,
         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request =
                (HttpServletRequest) req;
        HttpServletResponse response =
                (HttpServletResponse) res;

        String urlstr = request.getRequestURI();
        String token = request.getParameter("token");
        if(token==null) {
            token = request.getHeader("token");
        }

        if(token!=null) {
            List<Map> users =
                    systemUserDao.find_systemUser_by_token(token);
            if (users.size() == 1) {
                chain.doFilter(req, res);
                return;
            }
        }

        boolean isok = false;
        for(String str:whitelist){
            if(urlstr.contains(str)){
                chain.doFilter(req,res);
                isok = true;
                break;
            }
        }
        if(!isok){
            response.sendRedirect("login.html");
        }
    }

    public static void main(String[] args) {

    }
}
